//index.js
//获取应用实例
const app = getApp()

var context = null;// 使用 wx.createContext 获取绘图上下文 context
var bottonNum = 0x01; //有几个按钮按下
var buttonState=0x02; //第几个按下
var joystickValueX=0x08;
var joystickValueY=0x09;



Page({
  data: {
    x: 0,
    y: 80,
    R: 60,
    hidden: true,
    //canvas宽高
    canvasw: 0,
    canvash: 0,
    inputText: 'Hello!',
    receiveText: '',
    name: '',
    connectedDeviceId: '',
    services: {},
    characteristics: {},
    connected: true,
    btnText: '断开连接'

  },
  start(e) {

  },
  move(e) {
    var that = this
    var ctx = context

    var self = this;
    var touchX = e.changedTouches[0].x
    var touchY = e.changedTouches[0].y
    var movePos = that.GetPosition(touchX, touchY);

    context.beginPath()
    context.arc(movePos.posX, movePos.posY, 30, 0, 2 * Math.PI)
    context.setFillStyle('#EEEEEE')
    context.fill()

    context.beginPath()
    context.arc(that.data.x, that.data.y, that.data.R, 0, 2 * Math.PI);
    context.setStrokeStyle('#333333')
    context.stroke()

    context.draw();


  },
  end(e) {
    var that = this

    context.beginPath()
    context.arc(that.data.x, that.data.y, 30, 0, 2 * Math.PI)
    context.setFillStyle('#EEEEEE')
    context.fill()

    context.beginPath()
    context.arc(that.data.x, that.data.y, that.data.R, 0, 2 * Math.PI);
    context.setStrokeStyle('#333333')
    context.stroke()


    context.draw();

  },

  //画布初始化执行
  startCanvas: function () {
    var that = this;
    //创建canvas
    this.initCanvas();
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        //that.data.canvasw = res.windowWidth - 0;//设备宽度
        //that.data.canvash = that.data.canvasw;
        that.setData({
          'canvasw': res.windowWidth,
          'canvash': res.windowWidth,
          'x': res.windowWidth / 2 / 2,


        });

        context.beginPath()
        context.arc(that.data.x, that.data.y, 30, 0, 2 * Math.PI)
        context.setFillStyle('#EEEEEE')
        context.fill()

        context.beginPath()
        context.arc(that.data.x, that.data.y, that.data.R, 0, 2 * Math.PI);
        context.setStrokeStyle('#333333')
        context.stroke()


        context.draw();

      }
    });

  },
  //初始化函数
  initCanvas: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');

  },
  //事件监听
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },

  //获得触碰位置并且进行数据处理获得触碰位置与拖动范围的交点位置
  GetPosition: function (touchX, touchY) {
    var self = this;
    var DValue_X;
    var Dvalue_Y;
    var Dvalue_Z;
    var imageX;
    var imageY;
    var ratio;
    DValue_X = touchX - self.data.x;
    Dvalue_Y = touchY - self.data.y;
    Dvalue_Z = Math.sqrt(DValue_X * DValue_X + Dvalue_Y * Dvalue_Y);
    //console.log('touchX'+touchX+' touchY'+touchY+' x'+self.data.x+' y'+self.data.y+' Dx'+DValue_X+' Dy'+Dvalue_Y+' Dz'+Dvalue_Z)
    //触碰点在范围内
    if (Dvalue_Z <= self.data.R) {
      imageX = touchX;
      imageY = touchY;
      imageX = Math.round(imageX);
      imageY = Math.round(imageY);
      return { posX: imageX, posY: imageY };
    }

    //触碰点在范围外
    else {
      //console.log('范围外')

      ratio = self.data.R / Dvalue_Z;
      imageX = DValue_X * ratio + self.data.x;
      imageY = Dvalue_Y * ratio + self.data.y;
      imageX = Math.round(imageX);
      imageY = Math.round(imageY);
      return { posX: imageX, posY: imageY };
    }
  },


  onLoad: function (options) {
    console.log('index onload')
    //画布初始化执行
    this.startCanvas();

    var that = this
    console.log(options)
    that.setData({
      name: options.name,
      connectedDeviceId: options.connectedDeviceId
    })
if(options.name!=null)
{    
  console.log('options is not null')
  console.log('name:'+that.data.name+' id:'+that.data.connectedDeviceId)
  wx.getBLEDeviceServices({
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        console.log('the services:')
        console.log(res.services)
        that.setData({
          services: res.services
        })
        wx.getBLEDeviceCharacteristics({
          deviceId: options.connectedDeviceId,
          serviceId: res.services[1].uuid,
          success: function (res) {
            console.log('the characteristics:')
            console.log(res.characteristics)
            that.setData({
              characteristics: res.characteristics
            })
            wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId: options.connectedDeviceId,
              serviceId: that.data.services[1].uuid,
              characteristicId: that.data.characteristics[0].uuid,
              success: function (res) {
                console.log('启用notify成功')
              },
              fail:function(res){
                console.log('启用notify失败：')
                console.log(res)
                if(res.errCode==10009){
                  wx.showModal({
                    title: '提示',
                    content: '当前手机不支持BLE，请更换手机测试',
                    showCancel: false,
                    success: function (res) {
                      that.setData({
                        searching: false
                      })
                    }
                  })
                }
              }
            })
          }
        })
      }
    })
    wx.onBLEConnectionStateChange(function (res) {
      console.log('bt state:'+res.connected)
      that.setData({
        connected: res.connected
      })
    })
    wx.onBLECharacteristicValueChange(function (res) {
      var receiveText = app.buf2string(res.value)
      console.log('接收到数据：' + receiveText)
      that.setData({
        receiveText: receiveText
      })
    })


}

  },
  
  onReady: function () {
    console.log('index  onReady')
  },
  onShow: function () {
    console.log('index onShow')
  },
  onHide: function () {
    console.log('index onHide')
  },
  onUnload: function () {
    console.log('index onUnload')
    wx.closeBLEConnection({
      deviceId,
      success(res) {
        console.log(res)
      }
    })
  },

  searchBT:function(){
    wx.navigateTo({
      url: '../search/search'
    })
  },
  btTouchStart:function(e){
    console.log('btTouchStart')
    console.log(e.target.id)
    bottonNum=1;
    
  },

  btTouchEnd:function(e){
    console.log('btTouchEnd')
    bottonNum=0;
    this.SendPacktBLE();
  },
  /*
  bt_press: function (e) {
    var that = this;
    console.log('on  press');
    buttonState = e.target.id;
    
    
  },*/



	//数据协议打包发送
	//协议规则: 前三字节固定55 aa 11，第四字节为按钮按下个数，第五字节为摇杆动作标志(00-03)，第6-n为按钮编号(根据按钮按下个数定字节数，若为0则无此字节),接下来两字节表示摇杆x与y方向坐标(原点左下角，0-255)，接下来两字节留空为0,最后一字节为校验位(前面所有字节和与0xff取余)
	 SendPacktBLE:function()
	{

console.log('sendpack start')
     var packt = new Uint8Array(10 + bottonNum);//至少10字节+按钮按下的个球

  packt[0] = 0x55;
  packt[1] = 0xaa;
  packt[2] = 0x11;
  packt[3] = bottonNum;//小程序中只有单个按钮按下的情况
  packt[4] = 0x01;//摇杆所在区域

     if (bottonNum == 1) {
       packt[5] = buttonState;//几号按钮按下
     }

  packt[5 + bottonNum] = joystickValueX;
  packt[6 + bottonNum] = joystickValueY;

  var temp = 0;
  for (var ii = 0; ii < packt.length; ii++)
  {
    temp = temp + packt[ii];
  }
  packt[9+bottonNum] = (temp % 0xff);
console.log(packt)
  this.serialSend(packt);

  packt = null;



	},
  serialSend:function(pk){
    var that = this
    console.log('send press')
    if (that.data.connected) {
      const buffer = new ArrayBuffer(pk.length)
      const dataView = new Uint8Array(buffer)
      for (var i = 0; i < pk.length; i++) {
        dataView[i] = pk[i]
      }
      //const buffer = new ArrayBuffer(1)
      //const dataView = new DataView(buffer)

     // dataView.setUint8(0, 66)  //对应ascii字符B

      console.log(buffer)
      console.log(that.data.services)

      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.services[1].uuid,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function (res) {
          console.log('发送成功')
        },
        fail:function(res){
          console('发送失败')
          console(res)

        }
      })
    }
    else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function (res) {
          that.setData({
            searching: false
          })
        }
      })
    }
  }


})
